/**
 * 
 */
package com.lanswon.qzsmk.service.cardManageService.impl;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lanswon.qzsmk.base.AccountContants;
import com.lanswon.qzsmk.base.AppContants;
import com.lanswon.qzsmk.base.BlackListContants;
import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.dao.AccTxnDtlMapper;
import com.lanswon.qzsmk.dao.AppKindMapper;
import com.lanswon.qzsmk.dao.AppOpenRegMapper;
import com.lanswon.qzsmk.dao.BatchCollectionMapper;
import com.lanswon.qzsmk.dao.BlackListGenMapper;
import com.lanswon.qzsmk.dao.BlackListRcMapper;
import com.lanswon.qzsmk.dao.BusinessMapper;
import com.lanswon.qzsmk.dao.CardControlMapper;
import com.lanswon.qzsmk.dao.CardDataMapper;
import com.lanswon.qzsmk.dao.CardManageMapper;
import com.lanswon.qzsmk.dao.CardProdunctDefinitionMapper;
import com.lanswon.qzsmk.dao.CardTypeMapper;
import com.lanswon.qzsmk.dao.CertMapper;
import com.lanswon.qzsmk.dao.CertificateMapper;
import com.lanswon.qzsmk.dao.CorporationMapper;
import com.lanswon.qzsmk.dao.FeeRulesMapper;
import com.lanswon.qzsmk.dao.MainAccountPersonalMapper;
import com.lanswon.qzsmk.dao.PersonalMapper;
import com.lanswon.qzsmk.dao.QueryCardInfoMapper;
import com.lanswon.qzsmk.dao.SingleSellCardViewMapper;
import com.lanswon.qzsmk.dao.SubaccountPersonalMapper;
import com.lanswon.qzsmk.dao.TransGlideMapper;
import com.lanswon.qzsmk.dao.TxnDtlMapper;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.model.AppKind;
import com.lanswon.qzsmk.model.AppOpenReg;
import com.lanswon.qzsmk.model.BatchCollection;
import com.lanswon.qzsmk.model.BlackListGen;
import com.lanswon.qzsmk.model.Business;
import com.lanswon.qzsmk.model.CardControl;
import com.lanswon.qzsmk.model.CardData;
import com.lanswon.qzsmk.model.CardManage;
import com.lanswon.qzsmk.model.CardProdunctDefinition;
import com.lanswon.qzsmk.model.CardType;
import com.lanswon.qzsmk.model.Cert;
import com.lanswon.qzsmk.model.Certificate;
import com.lanswon.qzsmk.model.Corporation;
import com.lanswon.qzsmk.model.FeeRules;
import com.lanswon.qzsmk.model.MainAccountPersonal;
import com.lanswon.qzsmk.model.Personal;
import com.lanswon.qzsmk.model.SingleSellCardView;
import com.lanswon.qzsmk.model.SubaccountPersonal;
import com.lanswon.qzsmk.model.TransGlide;
import com.lanswon.qzsmk.model.TxnDtl;
import com.lanswon.qzsmk.service.cardManageService.SellCardService;
import com.lanswon.qzsmk.service.preService.BikeService;
import com.lanswon.qzsmk.util.CommonUtil;
import com.lanswon.qzsmk.util.CopyBean;
import com.lanswon.qzsmk.util.ExportExcel;
import com.lanswon.qzsmk.util.SequenceNumberUtil;
import com.lanswon.qzsmk.vo.DownloadBatchSellCardVo;
import com.lanswon.qzsmk.vo.FeeRulesVo;
import com.lanswon.qzsmk.vo.ReadCardVo;
import com.lanswon.qzsmk.vo.SellCardVo;
import com.lanswon.qzsmk.vo.VoucherVo;

/**
 * @author sun
 *
 */
@Service
@Transactional
public class SellCardServiceImpl implements SellCardService {
	
	@Autowired
	PersonalMapper pm;

	@Autowired
	BatchCollectionMapper bcm;

	@Autowired
	CardProdunctDefinitionMapper cpdm;

	@Autowired
	CorporationMapper cm;

	@Autowired
	BusinessMapper bm;

	@Autowired
	CertMapper cem;

	@Autowired
	CardControlMapper ccm;

	@Autowired
	CardDataMapper cdm;

	@Autowired
	CardManageMapper cmm;

	@Autowired
	SingleSellCardViewMapper sscvm;

	@Autowired
	CertificateMapper cfm;

	@Autowired
	CardTypeMapper ctm;

	// @Autowired
	// OnlSubaccountPersonalMapper ospm;

	@Autowired
	AppOpenRegMapper aorm;

	@Autowired
	BlackListGenMapper blgm;

	@Autowired
	BlackListRcMapper blrm;

	@Autowired
	AccTxnDtlMapper atdm;

	@Autowired
	MainAccountPersonalMapper mapm;

	@Autowired
	AppKindMapper akm;

	@Autowired
	SubaccountPersonalMapper spm;
	
	@Autowired
	QueryCardInfoMapper qcm;
	
	@Autowired
	TxnDtlMapper tdm;
	
	@Autowired
	FeeRulesMapper frsm;
	
	@Autowired
	TransGlideMapper tgm;
	
	@Autowired
	BikeService bikeService;

	@Override
	public DwzPage<SellCardVo> queryBatchSellCard(SellCardVo scv) {
		scv.setClaimStatus(CardContants.CLAIM_STATUS_TOGIVE);
		List<BatchCollection> l = bcm.queryBatchSellCard(scv);
		List<SellCardVo> ls = new ArrayList<>();
		for (BatchCollection bc : l) {
			SellCardVo s = new SellCardVo();
			s.setApplyBatchNo(bc.getApplyBatchNo());
			s.setCollBranchName(bc.getCollBranchName());
			s.setCardPCodeName(cpdm.queryCardPCode(bc.getCardPCode()).getCardpName());
			s.setRecordNum(bc.getRecordNum());
			s.setApplyDate(bc.getApplyDate());
			s.setCollBranchNo(bc.getCollBranchNo());
			s.setWorkCorp(cm.queryCorporationByCode(bc.getCorpCode()).getCorpName());
			ls.add(s);

		}

		int totalCount = bcm.queryBatchSellCardCount(scv);

		DwzPage<SellCardVo> dp = new DwzPage<SellCardVo>(scv.getCurrentPage(), scv.getNumPerPage(), totalCount);
		dp.setList(ls);
		return dp;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public Cert commitBatchSellCardInfo(SellCardVo scv) {

		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		Corporation c = cm.queryCorporationByApplyBatchNo(scv.getApplyBatchNo());
		CardProdunctDefinition cpd = cpdm.queryCardPCodeByCardProductName(scv.getCardPCodeName());

		Date currentTime = new Date();
		List<CardControl> list = ccm.queryCardControlByApplyBatchNo(scv.getApplyBatchNo());
		for (CardControl cc : list) {
			CardData cd = cdm.queryCardDataById(cc.getCardDataId());
			Personal p = pm.queryPersonalByCustomerNo(cd.getCustomerNo());

			// 业务流水表
			Business b = new Business();
			b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
			b.setAgentName(scv.getAgentName());// 代理人姓名
			b.setAgentPaperNo(scv.getAgentPaperNo());// 代理人证件号码
			b.setAgentPapertype(scv.getAgentPapertype());// 代理人证件类型
			b.setAgentPhone(scv.getAgentPhone());// 代理人联系电话
			b.setBatchNo(scv.getApplyBatchNo());// 批次号
			b.setBusiNum(scv.getRecordNum());// 业务数量啥子吆
			b.setCardControlId(cc.getCardControlId());// 卡控制号 批量用不上
			b.setCardpCode(cpd.getCardpCode());// 卡产品
			// b.setCertNo(certNo);/凭证编号

			b.setCorpNo(c.getCorpNo());// 单位编号 批量办理时使用
			// b.setCustomerNo(p.getCustomerNo());// 客户编号
			b.setRemark("這是批量申請業務表");// 备注
			// b.setRptDate(rptDate);//轧帐日期
			// b.setRptFlag(rptFlag);//轧帐标识
			b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
			b.setTransAuthId("业务授权人编号001");// 业务授权人编号
			b.setTransAuthName("业务授权人姓名");// 业务授权人姓名
			// b.setTransCode(transCode);//交易代码
			// b.setTransDate(transDate);//交易日期
			//
			
			// 凭证表
			Cert ce = new Cert();
			ce.setBusinessNo(b.getBusinessNo());
			ce.setCertNo(SequenceNumberUtil.generatorCertNo());
			ce.setAgentName(scv.getAgentName());// 代领人的信息，领卡的时候在填写
			ce.setAgentPaperNo(scv.getAgentPaperNo());
			ce.setAgentPapertype(scv.getAgentPapertype());
			ce.setBranch(activeUser.getBranchName());// 网点名称
			ce.setBranchNo(activeUser.getBranchNo());// 网点编号
			ce.setBusinessNo(b.getBusinessNo());// 业务流水号
			 ce.setCardControlId(cc.getCardControlId());
			ce.setCertType(CardContants.BATCH_CARD);// 凭证类型 1 单笔申请 2 批量申请 3 出库配送 4
													// 单笔发卡 5 批量发卡
			ce.setCardpCode(cpd.getCardpCode());// 卡产品代码
			ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
														// 3.非记名衍生卡
			ce.setCorpCode(c.getCorpCode());// 单位编号id
			ce.setCorpName(c.getCorpName());// 单位名称
			ce.setCrtDate(currentTime);
			ce.setCrtOperator(activeUser.getUserNo().toString());
			ce.setData("打印凭证数据--路径 ");// 打印凭证数据
			ce.setLastDate(currentTime);
			ce.setLastOperator(activeUser.getUserNo().toString());
			// ce.setName(p.getCustomerName());// 持卡人姓名
			// ce.setPaperNo(p.getPaperNo());
			// ce.setPaperType(p.getPaperType());
			ce.setPrintCount(1);// 打印次数
			// ce.setTransCode(transCode);//交易代码
			cem.insert(ce);
			b.setCertNo(ce.getCertNo());// 凭证编号
			bm.insert(b);

			
			
			CardManage cardm = new CardManage();
			cardm.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			cardm.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
			cardm.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
			cardm.setCustomerNo(cd.getCustomerNo());
			cardm.setCardpCode(cd.getCardpCode());
			cardm.setCardTypecode(cd.getCardTypecode());
			cardm.setCitizenCardNo(cd.getCitizenCardNo());
			cardm.setCardPosition(CardContants.CARD_STATE_NORMAL);
			cardm.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cardm.setBatchNo(scv.getApplyBatchNo());
			cardm.setApplyWay(CardContants.CLAIM_METHOD_COMPANY);
			cardm.setApplyBranchNo(activeUser.getBranchNo());
			cardm.setApplyBranch(activeUser.getBranchName());
			cardm.setApplyDate(currentTime);
			cardm.setApplyTellerNo(activeUser.getUserNo().toString());
			cardm.setCertNo(ce.getCertNo());
			cardm.setBusinessNo(b.getBusinessNo());
			cmm.insert(cardm);

			cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cc.setClaimStatus(CardContants.CLAIM_STATUS_GIVEN);
			// cc.setApplyDate(currentTime);
			cc.setLastDate(currentTime);
			cc.setReleaseDate(currentTime);
			cc.setLastOperator(activeUser.getUserNo().toString());
			cc.setCurrProcId(cardm.getProcessId());
			cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
			ccm.updateCardControl(cc);

			MainAccountPersonal m = mapm.queryMainAccountPersonalByCustomerNo(cd.getCustomerNo());
			if (m == null) {
				m = new MainAccountPersonal();
				m.setAccountName(p.getCustomerName());
				m.setCustomerNo(cd.getCustomerNo());
				m.setAccoBranchNo(activeUser.getBranchNo());
				m.setAccoTellerNo(activeUser.getUserNo().toString());
				m.setAccoDate(currentTime);
				m.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
				mapm.insert(m);
			}

			// 开通应用 默认开通 -公交应用

			AppKind ak = akm.queryAppKindByAppFalg(AppContants.APP_FLAG_TRANSIT);
			// AppOpenReg aor =
			// aorm.queryAppOpenRegByAppType(ak.getAppType().toString());

			AppOpenReg ao = new AppOpenReg();
			ao.setCitizenCardNo(cd.getCitizenCardNo());
			ao.setAppType(ak.getAppType().toString());
			ao.setOpenDate(currentTime);

			if (ak.getValidMonthNum() != null) {

				ao.setIsValid(AppContants.APP_ISVALID); // 月份计算
				ao.setValidBegin(currentTime);
				ao.setValidEnd(CommonUtil.willDate(currentTime, ak.getValidMonthNum()));

			} else {
				ao.setIsValid(AppContants.APP_NOVALID); // 月份计算
			}

			// ao.setStopDate(a.getStopDate());//停用日期
			// ao.setRetrieveDate(a.getRetrieveDate());//恢复日期
			ao.setAppStatus(AppContants.APP_STATUS_OPEN);// 应用状态
			ao.setRemark("批量售卡，默认开通公交3F01应用");
			ao.setCrtOperator(activeUser.getUserNo().toString());
			ao.setCrtDate(currentTime);
			ao.setLastOperator(activeUser.getUserNo().toString());
			ao.setLastDate(currentTime);
			ao.setIsDeposit(AccountContants.IS_DEPOSIT_NO);
			aorm.insert(ao);

			//
			// 钱包1
			SubaccountPersonal cardWallet = new SubaccountPersonal();
			cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
			cardWallet.setAccoDate(currentTime);// 开户日期
			cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
			cardWallet.setAccountName(p.getCustomerName());// 户名
			cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
			// cardWallet.setAccountSign(accountSign);//帐户标识
			cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
			cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK);// 所属钱包类型id
																					// 01-电子存折
																					// 02-电子钱包
			cardWallet.setAppFlag(ak.getAppFlag());// 应用标识 默认开通公交
			// cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
			cardWallet.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
			cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
			// cardWallet.setClsDate(clsDate);//销户日期
			// cardWallet.setClsTellerNo(clsTellerNo);//销户柜员号
			cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
			// cardWallet.setCrdNo(crdNo);//卡内号
			cardWallet.setCurrCount(0);// 当前计数器值
			cardWallet.setCustomerNo(p.getCustomerNo());// 客户编号
			cardWallet.setErrorDegree((short) 0);// 输错次数
			cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
			// cardWallet.setFreezeDate(freezeDate);//冻结日期
			cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
			// cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
			// cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
			// cardWallet.setLastTransDate(lastTransDate);//最后交易日
			// cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
			// cardWallet.setLossDate(lossDate);//挂失日期
			cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
			cardWallet.setMainaccountNo(m.getMainaccountNo());// 主帐户号
			cardWallet.setMaxCount(0);// 最大计数器值
			// cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
			// cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
			cardWallet.setPasswordStatus(null);// 密码标志
			cardWallet.setProductNumber(0);// 积数
			cardWallet.setRemark("这是批量售卡 ，开户-卡应用钱包");
			cardWallet.setSumJe(0);// 消费积分
			cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
			cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
			cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
			cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
			cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
			cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
			cardWallet.setTotalReloadCnt(0);// 累计充值笔数
			cardWallet.setValidDate(null);// 有效期
			spm.insert(cardWallet);

			// 钱包2
			cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 钱包类型
			spm.insert(cardWallet);

		}

		// 业务流水表
		Business b = new Business();
		b.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
		b.setAgentName(scv.getAgentName());// 代理人姓名
		b.setAgentPaperNo(scv.getAgentPaperNo());// 代理人证件号码
		b.setAgentPapertype(scv.getAgentPapertype());// 代理人证件类型
		b.setAgentPhone(scv.getAgentPhone());// 代理人联系电话
		b.setBatchNo(scv.getApplyBatchNo());// 批次号
		b.setBusiNum(scv.getRecordNum());// 业务数量啥子吆
		// b.setCardControlId(cc.getCardControlId());// 卡控制号 批量用不上
		b.setCardpCode(cpd.getCardpCode());// 卡产品
		// b.setCertNo(certNo);/凭证编号

		b.setCorpNo(c.getCorpNo());// 单位编号 批量办理时使用
		// b.setCustomerNo(p.getCustomerNo());// 客户编号
		b.setRemark("這是批量申請業務表");// 备注
		// b.setRptDate(rptDate);//轧帐日期
		// b.setRptFlag(rptFlag);//轧帐标识
		b.setTellerNo(activeUser.getUserNo().toString());// 柜员号
		b.setTransAuthId("业务授权人编号001");// 业务授权人编号
		b.setTransAuthName("业务授权人姓名");// 业务授权人姓名
		// b.setTransCode(transCode);//交易代码
		// b.setTransDate(transDate);//交易日期
		//
		
		// 凭证表
		Cert ce = new Cert();
		ce.setBusinessNo(b.getBusinessNo());
		ce.setCertNo(SequenceNumberUtil.generatorCertNo());
		ce.setAgentName(scv.getAgentName());// 代领人的信息，领卡的时候在填写
		ce.setAgentPaperNo(scv.getAgentPaperNo());
		ce.setAgentPapertype(scv.getAgentPapertype());
		ce.setBranch(activeUser.getBranchName());// 网点名称
		ce.setBranchNo(activeUser.getBranchNo());// 网点编号
		ce.setBusinessNo(b.getBusinessNo());// 业务流水号
		// ce.setCardControlId(cc.getCardControlId());
		ce.setCertType(CardContants.BATCH_CARD);// 凭证类型 1 单笔申请 2 批量申请 3 出库配送 4
												// 单笔发卡 5 批量发卡
		ce.setCardpCode(cpd.getCardpCode());// 卡产品代码
		ce.setCardTypecode(cpd.getCardTypeCode());// 卡类型代码 1.标准卡 2.记名衍生卡
													// 3.非记名衍生卡
		ce.setCorpCode(c.getCorpCode());// 单位编号id
		ce.setCorpName(c.getCorpName());// 单位名称
		ce.setCrtDate(currentTime);
		ce.setCrtOperator(activeUser.getUserNo().toString());
		ce.setData("打印凭证数据--路径 ");// 打印凭证数据
		ce.setLastDate(currentTime);
		ce.setLastOperator(activeUser.getUserNo().toString());
		// ce.setName(p.getCustomerName());// 持卡人姓名
		// ce.setPaperNo(p.getPaperNo());
		// ce.setPaperType(p.getPaperType());
		ce.setPrintCount(1);// 打印次数
		// ce.setTransCode(transCode);//交易代码
		cem.insert(ce);
		String str = "{\"title\":\""+"批量发卡凭证"+"\",\"type\":\""+"batchCard"+"\",\"certNo\":\""+ce.getCertNo()+"\",\"busType\":\""
		+CardContants.getCertTypeNameByCode(ce.getCertType())+"\",\"cardType\":\""+ce.getCardTypecode()+"\",\"corpName\":\""
		+ce.getCorpName()+"\",\"cardpName\":\""+cpdm.queryCardPCode(ce.getCardpCode()).getCardpName()+"\",\"recordNum\":\""
		+scv.getRecordNum()+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""
		+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
		ce.setData(str);
		ce.setTransCode("批量发卡");
		cem.update(ce);
		b.setCertNo(ce.getCertNo());// 凭证编号
		bm.insert(b);

		return ce;
	}

	@Override
	public DwzPage<SingleSellCardView> querySingleSellCard(SellCardVo scv) {// 不卡换卡
																			// 查詢的時候如果当
																			// 到了预计领卡日期
																			// 显示带发放
																			// 没到
																			// 显示已经申请
		scv.setClaimStatus(CardContants.CLAIM_STATUS_APPLY);
		scv.setClaimStatus2(CardContants.CLAIM_STATUS_SUPPLEMENTARY_CARD_APPLICATION);
		scv.setClaimStatus3(CardContants.CLAIM_STATUS_CHANGE_CARD_APPLICATION);
		scv.setCertStatus(CardContants.CERT_STATUS_VALID);
		scv.setCertType(CardContants.SINGLE_APPLICATION);
		scv.setCertType2(CardContants.CARD_ISSUING_APPLY);
		scv.setCertType3(CardContants.CARD_CHANGE_APPLY);
		List<SingleSellCardView> list = sscvm.querySingleSellCard(scv);
		int totalCount = sscvm.querySingleSellCardCount(scv);
		List<SingleSellCardView> ll = new ArrayList<>();
		for (SingleSellCardView sscv : list) {
			sscv.setPaperTypeName(cfm.queryCertificateByCode(sscv.getPaperType()).getCertificatesName());
			sscv.setApplyTypeName(CardContants.getApplyTypeNameByCode(sscv.getApplyType()));
			sscv.setClaimStatusName(CardContants.getClaimStatusNameByCode(sscv.getClaimStatus()));
			// CardControl cc =
			// ccm.queryCardControlByCitizenCardNo(sscv.getCitizenCardNo());
			// if(CardContants.CLAIM_STATUS_SUPPLEMENTARY_CARD_APPLICATION.equals(cc.getClaimStatus())
			// ||
			// CardContants.CLAIM_STATUS_CHANGE_CARD_APPLICATION.equals(cc.getClaimStatus())){
			// if(sscv.getApplyDate().getTime()<System.currentTimeMillis()){
			//
			// cc.setCardPosition(CardContants.CARD_POSITION_COUNTER_EMPLOYEE);
			// cc.setClaimStatus(CardContants.CLAIM_STATUS_TOGIVE);
			// cc.setLastDate(currentTime);
			// cc.setLastOperator("操作员--小花");
			// ccm.updateCardControl(cc);
			// sscv.setApplyTypeName(CardContants.getApplyTypeNameByCode(sscv
			// .getApplyType()));
			//
			// }
			// }

			ll.add(sscv);
		}

		DwzPage<SingleSellCardView> dp = new DwzPage<>(scv.getCurrentPage(), scv.getNumPerPage(), totalCount);
		dp.setList(ll);

		return dp;
	}

	/**
	 * scv :证件类型名称/号码 原卡号 新卡号 卡产品 申领类别名称 姓名 代理人信息
	 * @throws ApplicationException 
	 */
	@Override
	@Transactional(rollbackFor=Exception.class,propagation=Propagation.REQUIRED)
	public VoucherVo commitSingleSellCardInfo(SellCardVo scv) throws ApplicationException {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		//判断新卡   是否已使用
		CardControl ccl = ccm.queryCardControlByCitizenCardNo(scv.getNewCitizenCardNo());
		if(!ccl.getCardStatus().equals(CardContants.CARD_STATE_DISABLED)){
			throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "当前新卡已投入使用，无法发放");
		}

		Date currentTime = new Date();

		Certificate cf = cfm.queryCertificateByName(scv.getPaperTypeName());

		VoucherVo vv = new VoucherVo();
		
		Business bu = new Business();
		Cert cert = new Cert();
		// 补卡或者换卡
		CardData cd=null;

		if (StringUtils.isNotEmpty(scv.getOldCitizenCardNo())) {
			 cd= cdm.queryCardDataByCitizenCardNo(scv.getNewCitizenCardNo());// 不记名卡

			CardData cdd = cdm.queryCardDataByOldCitizenCardNo(scv.getOldCitizenCardNo());// 带个人信息--                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  数据

			cdd = (CardData) CopyBean.copyA2b(cd, cdd);

			CardControl c = ccm.queryCardControlByCardDataId(cd.getCardDataId());//  不记名卡

			CardControl cc1 = ccm.queryCardControlByCardDataId(cdd.getCardDataId());// 带个人信息-- 

			cc1 = (CardControl) CopyBean.copyA2b(c, cc1);
			
			
			//ccm.updateCardControl(cc1);

			ccm.deleteCardControlByCardControlId(c.getCardControlId());

			cdm.deleteCardDataByNewCitizenCardNo(cd.getCitizenCardNo());

			cdm.update(cdd);

			Personal p = pm.queryPersonalByPaperNo(cf.getCertificateType(), scv.getPaperNo());
			List<CardManage> lcm = cmm.queryCardManageByPaperNo(p.getCustomerNo(), cdd.getCardpCode());
			for (CardManage cm : lcm) {
				if(StringUtils.isEmpty(cm.getCitizenCardNo())){
					cm.setCitizenCardNo(scv.getNewCitizenCardNo());
					cmm.update(cm);
				}
			}

			MainAccountPersonal m = mapm.queryMainAccountPersonalByCustomerNo(cdd.getCustomerNo());

			
			AppKind ak_3F01 = akm.queryAppKindByAppFalg("3F01");
			// //原卡中的应用===>转移到新卡，原卡应用关闭
			List<AppOpenReg> la = aorm.queryAppOpenRegByRemark2(scv.getOldCitizenCardNo(),AppContants.APP_STATUS_CLOSE_SUPPLEMENTCARD,AppContants.APP_STATUS_CLOSE_CHANGECARD);
			for (AppOpenReg a : la) {
				AppOpenReg ao = new AppOpenReg();
				ao.setCitizenCardNo(scv.getNewCitizenCardNo());
				ao.setAppType(a.getAppType());
				ao.setOpenDate(currentTime);
				ao.setIsValid(a.getIsValid());
				ao.setIsDeposit(AccountContants.IS_DEPOSIT_NO);
				ao.setValidBegin(a.getValidBegin());
				ao.setValidEnd(a.getValidEnd());
//				ao.setStopDate(a.getStopDate());
//				ao.setRetrieveDate(a.getRetrieveDate());
				ao.setAppStatus(AppContants.APP_STATUS_OPEN);
				ao.setRemark("补/换卡 应用转移");
				ao.setCrtOperator(activeUser.getUserNo().toString());
				ao.setCrtDate(currentTime);
				ao.setLastOperator(activeUser.getUserNo().toString());
				ao.setLastDate(currentTime);
				aorm.insert(ao);

				
				a.setIsDeposit(AccountContants.IS_DEPOSIT_YES);
				a.setLastOperator(activeUser.getUserNo().toString());
				a.setLastDate(currentTime);

				aorm.update(a);

				// 钱包1
				SubaccountPersonal cardWallet = new SubaccountPersonal();
				cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
				cardWallet.setAccoDate(currentTime);// 开户日期
				cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
				cardWallet.setAccountName(p.getCustomerName());// 户名
				cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
				// cardWallet.setAccountSign(accountSign);//帐户标识
				cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
				cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK);// 所属钱包类型id 01-电子存折 02-电子钱包
				cardWallet.setAppFlag(ak_3F01.getAppFlag());// 应用标识
																						// 默认开通公交
				// cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
				cardWallet.setCitizenCardNo(cdd.getCitizenCardNo());// 市民卡号
				cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
				// cardWallet.setClsDate(clsDate);//销户日期
				// cardWallet.setClsTellerNo(clsTellerNo);//销户柜员号
				cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
				// cardWallet.setCrdNo(crdNo);//卡内号
				cardWallet.setCurrCount(0);// 当前计数器值
				cardWallet.setCustomerNo(p.getCustomerNo());// 客户编号
				cardWallet.setErrorDegree((short) 0);// 输错次数
				cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
				// cardWallet.setFreezeDate(freezeDate);//冻结日期
				cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
				// cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
				// cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
				// cardWallet.setLastTransDate(lastTransDate);//最后交易日
				// cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
				// cardWallet.setLossDate(lossDate);//挂失日期
				cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
				cardWallet.setMainaccountNo(m.getMainaccountNo());// 主帐户号
				cardWallet.setMaxCount(0);// 最大计数器值
				// cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
				// cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
				cardWallet.setPasswordStatus(null);// 密码标志
				cardWallet.setProductNumber(0);// 积数
				cardWallet.setRemark("这是备注");
				cardWallet.setSumJe(0);// 消费积分
				cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
				cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
				cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
				cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
				cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
				cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
				cardWallet.setTotalReloadCnt(0);// 累计充值笔数
				cardWallet.setValidDate(null);// 有效期
				spm.insert(cardWallet);

				// 钱包2
				cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 钱包类型
				spm.insert(cardWallet);

			}
			
			// 补卡
			CardManage c1 = new CardManage();
			c1.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			c1.setApplyBranch(activeUser.getBranchName());
			c1.setApplyBranchNo(activeUser.getBranchNo());
			c1.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
			c1.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
			c1.setApplyTellerNo(activeUser.getUserNo().toString());
			c1.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
			c1.setCardpCode(cdd.getCardpCode());
			c1.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			c1.setCardStatus(CardContants.CARD_STATE_NORMAL);
			c1.setCardTypecode(cdd.getCardTypecode());
			c1.setCustomerNo(p.getCustomerNo());
			c1.setRemark("单笔补/换发卡");
			c1.setApplyDate(currentTime);
			c1.setCitizenCardNo(scv.getNewCitizenCardNo());

			cmm.insert(c1);

			cc1.setReleaseDate(currentTime);// 发卡日期
			cc1.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			cc1.setDmgFlag(CardContants.CARD_UNDAMAGED);
			cc1.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cc1.setCurrProcId(c1.getProcessId());
			cc1.setLastDate(currentTime);
			cc1.setLastOperator(activeUser.getUserNo().toString());
			cc1.setRemark("补/换  新卡发放");
			cc1.setClaimStatus(CardContants.CLAIM_STATUS_GIVEN);
			cc1.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
			ccm.updateCardControl(cc1);
			
			cert.setCertNo(SequenceNumberUtil.generatorCertNo());
			cert.setCertType(CardContants.CARD_ISSUING_CARD);
			cert.setCardpCode(cdd.getCardpCode());
			cert.setCardTypecode(cdd.getCardTypecode());
			cert.setName(scv.getCustomerName());
			cert.setPaperNo(scv.getPaperNo());
			cert.setPaperType(cf.getCertificateType());
			cert.setBranch(activeUser.getBranchName());
			cert.setBranchNo(activeUser.getBranchNo());
			cert.setAgentName(scv.getAgentName());
			cert.setAgentPaperNo(scv.getAgentPaperNo());
			cert.setAgentPapertype(scv.getAgentPapertype());
			cert.setCardControlId(cc1.getCardControlId());
			cert.setCrtDate(new Date());
			cert.setCrtOperator(activeUser.getUserNo().toString());
			cert.setLastOperator(activeUser.getUserNo().toString());
			cert.setLastDate(new Date());
			cem.insert(cert);
			

			
			bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
			bu.setCustomerNo(cdd.getCustomerNo());
			bu.setCardControlId(cc1.getCardControlId());
			bu.setAgentName(scv.getAgentName());
			bu.setAgentPaperNo(scv.getAgentPaperNo());
			bu.setAgentPapertype(scv.getAgentPapertype());
			bu.setAgentPhone(scv.getAgentPhone());
			bu.setBusiNum(1);
			bu.setTellerNo(activeUser.getUserNo().toString());
			// bu.setTransDate(new Date());// 交易日期
			bu.setSeqStatus(CardContants.LSZT_NORMAL);
			bu.setRemark(scv.getRemark());
			bu.setCertNo(cert.getCertNo());
			bm.insert(bu);

			c1.setCertNo(cert.getCertNo());
			c1.setBusinessNo(bu.getBusinessNo());
			cmm.update(c1);
			
			cert.setBusinessNo(bu.getBusinessNo());
			cem.update(cert);
			
			//自行车应用
			AppKind aKind=akm.queryAppKindByAppFalg(AppContants.APP_FLAG_BIKE);
			for (AppOpenReg a : la) {
				if(a.getAppType().equals(aKind.getAppType().toString())){
					String newCardsn=(String) SecurityUtils.getSubject().getSession().getAttribute("newCardsn");
					String newCitizenCardNo=(String) SecurityUtils.getSubject().getSession().getAttribute("newCitizenCardNo");
					String oldVipno=(String) SecurityUtils.getSubject().getSession().getAttribute("oldVipno");
					String oldVipcardsn=(String) SecurityUtils.getSubject().getSession().getAttribute("oldVipcardsn");
					String newVipno=(String) SecurityUtils.getSubject().getSession().getAttribute("newVipno");
					String newVipcardsn=(String) SecurityUtils.getSubject().getSession().getAttribute("newVipcardsn");
					SecurityUtils.getSubject().getSession().removeAttribute("newVipcardsn");
					SecurityUtils.getSubject().getSession().removeAttribute("newCardsn");
					SecurityUtils.getSubject().getSession().removeAttribute("newCitizenCardNo");
					SecurityUtils.getSubject().getSession().removeAttribute("oldVipno");
					SecurityUtils.getSubject().getSession().removeAttribute("oldVipcardsn");
					SecurityUtils.getSubject().getSession().removeAttribute("newVipno");
					bikeService.successExchangeNewCard(newCardsn, newCitizenCardNo, oldVipno, oldVipcardsn, newVipno, newVipcardsn);
				}
			}

			vv.setCertNo(cert.getCertNo());
			vv.setOldCitizenCardNo(scv.getOldCitizenCardNo());
			vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(cert.getCertType()));
			vv.setCardType(cdd.getCardTypecode());

		} else {
			// 首次申领

			scv.setPaperType(cf.getCertificateType());
			cd = cdm.queryCardDataByPaperNo(scv);
			

			CardControl cc = ccm.queryCardControlByCardDataId(cd.getCardDataId());// 人
			CardControl cc1 = ccm.queryCardControlByCitizenCardNo(scv.getNewCitizenCardNo());// 卡
			cc = (CardControl) CopyBean.copyA2b(cc1, cc);
			//ccm.updateCardControl(cc);
			ccm.deleteCardControlByCardControlId(cc1.getCardControlId());//卡
			cdm.deleteCardDataByNewCitizenCardNo(scv.getNewCitizenCardNo());//卡
			
			cd.setCitizenCardNo(scv.getNewCitizenCardNo());
			cd.setCityCode(CardContants.CITY_CODE);
			cdm.update(cd);

			Personal p = pm.queryPersonalByCustomerNo(cd.getCustomerNo());

			CardManage c = new CardManage();
			c.setProcessId(UUID.randomUUID().toString().replace("-", ""));
			c.setApplyBranch(activeUser.getBranchName());
			c.setApplyBranchNo(activeUser.getBranchNo());
			c.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
			c.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
			c.setApplyTellerNo(activeUser.getUserNo().toString());
			c.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
			c.setCardpCode(cd.getCardpCode());
			c.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			c.setCardStatus(CardContants.CARD_STATE_NORMAL);
			c.setCardTypecode(cd.getCardTypecode());
			c.setCustomerNo(p.getCustomerNo());
			c.setRemark("单笔首次发卡");
			c.setApplyDate(currentTime);

			c.setCitizenCardNo(scv.getNewCitizenCardNo());
			cmm.insert(c);

			cc.setReleaseDate(currentTime);// 发卡日期
			cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
			cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
			cc.setDmgFlag(CardContants.CARD_UNDAMAGED);
			cc1.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
			cc.setLastOperator(activeUser.getUserNo().toString());
			cc.setLastDate(currentTime);
			cc.setRemark("首次申领  新卡发放");
			cc.setClaimStatus(CardContants.CLAIM_STATUS_GIVEN);
			cc.setCurrProcId(c.getProcessId());
			ccm.updateCardControl(cc);

			// 新卡子账户

			MainAccountPersonal m = mapm.queryMainAccountPersonalByCustomerNo(cd.getCustomerNo());
			if (m == null) {
				m = new MainAccountPersonal();
				m.setAccountName(scv.getCustomerName());
				m.setCustomerNo(cd.getCustomerNo());
				m.setAccoBranchNo(activeUser.getBranchNo());
				m.setAccoTellerNo(activeUser.getUserNo().toString());
				m.setAccoDate(currentTime);
				m.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
				mapm.insert(m);
			}


			// 开通应用 默认开通 -公交应用

			AppKind ak = akm.queryAppKindByAppFalg(AppContants.APP_FLAG_TRANSIT);
			// AppOpenReg aor =
			// aorm.queryAppOpenRegByAppType(ak.getAppType().toString());

			AppOpenReg ao = new AppOpenReg();
			ao.setCitizenCardNo(scv.getNewCitizenCardNo());
			ao.setAppType(String.valueOf(ak.getAppType()));
			ao.setOpenDate(currentTime);

			if (ak.getValidMonthNum() != null) {

				ao.setIsValid(AppContants.APP_ISVALID); // 月份计算
				ao.setValidBegin(currentTime);
				ao.setValidEnd(CommonUtil.willDate(currentTime, ak.getValidMonthNum()));

			} else {
				ao.setIsValid(AppContants.APP_NOVALID); // 月份计算
			}

			// ao.setStopDate(a.getStopDate());//停用日期
			// ao.setRetrieveDate(a.getRetrieveDate());//恢复日期
			ao.setAppStatus(AppContants.APP_STATUS_OPEN);// 应用状态
			ao.setRemark("单笔售卡，默认开通公交3F01应用");
			ao.setIsDeposit(AccountContants.IS_DEPOSIT_NO);
			ao.setCrtOperator(activeUser.getUserNo().toString());
			ao.setCrtDate(currentTime);
			ao.setLastOperator(activeUser.getUserNo().toString());
			ao.setLastDate(currentTime);
			
			aorm.insert(ao);

			// 钱包1
			SubaccountPersonal cardWallet = new SubaccountPersonal();
			cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
			cardWallet.setAccoDate(currentTime);// 开户日期
			cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
			cardWallet.setAccountName(p.getCustomerName());// 户名
			cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
			// cardWallet.setAccountSign(accountSign);//帐户标识
			cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
			cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_BANKBOOK);// 所属钱包类型id
																					// 01-电子存折
																					// 02-电子钱包
			cardWallet.setAppFlag(ak.getAppFlag());// 应用标识 默认开通公交
			// cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
			cardWallet.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
			cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
			// cardWallet.setClsDate(clsDate);//销户日期
			// cardWallet.setClsTellerNo(clsTellerNo);//销户柜员号
			cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
			// cardWallet.setCrdNo(crdNo);//卡内号
			cardWallet.setCurrCount(0);// 当前计数器值
			cardWallet.setCustomerNo(p.getCustomerNo());// 客户编号
			cardWallet.setErrorDegree((short) 0);// 输错次数
			cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
			// cardWallet.setFreezeDate(freezeDate);//冻结日期
			cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
			// cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
			// cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
			// cardWallet.setLastTransDate(lastTransDate);//最后交易日
			// cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
			// cardWallet.setLossDate(lossDate);//挂失日期
			cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
			cardWallet.setMainaccountNo(m.getMainaccountNo());// 主帐户号
			cardWallet.setMaxCount(0);// 最大计数器值
			// cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
			// cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
			cardWallet.setPasswordStatus(null);// 密码标志
			cardWallet.setProductNumber(0);// 积数
			cardWallet.setRemark("售卡，开通应用钱包");
			cardWallet.setSumJe(0);// 消费积分
			cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
			cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
			cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
			cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
			cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
			cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
			cardWallet.setTotalReloadCnt(0);// 累计充值笔数
			cardWallet.setValidDate(null);// 有效期

			spm.insert(cardWallet);

			// 钱包2
			cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 钱包类型
			spm.insert(cardWallet);

			
			cert.setCertNo(SequenceNumberUtil.generatorCertNo());
			cert.setCertType(CardContants.SINGLE_CARD);
			cert.setCardpCode(cd.getCardpCode());
			cert.setCardTypecode(cd.getCardTypecode());
			cert.setName(scv.getCustomerName());
			cert.setPaperNo(scv.getPaperNo());
			cert.setPaperType(cf.getCertificateType());
			cert.setBranch(activeUser.getBranchName());
			cert.setBranchNo(activeUser.getBranchNo());
			cert.setAgentName(scv.getAgentName() == null?scv.getCustomerName():scv.getAgentName());
			cert.setAgentPaperNo(scv.getAgentPaperNo() == null?scv.getPaperNo():scv.getAgentPaperNo());
			cert.setAgentPapertype(scv.getAgentPapertype()== null?scv.getPaperType():scv.getAgentPapertype());
			cert.setCardControlId(cc.getCardControlId());
			cert.setCrtDate(new Date());
			cert.setCrtOperator(activeUser.getUserNo().toString());
			cert.setLastOperator(activeUser.getUserNo().toString());
			cert.setLastDate(new Date());
			cem.insert(cert);

			
			bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
			bu.setCustomerNo(cd.getCustomerNo());
			bu.setCardControlId(cc.getCardControlId());
			bu.setAgentName(scv.getAgentName() == null?scv.getCustomerName():scv.getAgentName());
			bu.setAgentPaperNo(scv.getAgentPaperNo() == null?scv.getPaperNo():scv.getAgentPaperNo());
			bu.setAgentPapertype(scv.getAgentPapertype()== null?scv.getPaperType():scv.getAgentPapertype());
			bu.setAgentPhone(scv.getAgentPhone()== null?p.getMobile():scv.getAgentPhone());
			bu.setBusiNum(1);
			bu.setTellerNo(activeUser.getUserNo().toString());
			// bu.setTransDate(new Date());// 交易日期
			bu.setSeqStatus(CardContants.LSZT_NORMAL);
			bu.setRemark("首次领卡");
			bu.setCertNo(cert.getCertNo());
			bm.insert(bu);

			c.setCertNo(cert.getCertNo());
			c.setBusinessNo(bu.getBusinessNo());
			cert.setBusinessNo(bu.getBusinessNo());
			cmm.update(c);
			cem.update(cert);

			vv.setCertNo(cert.getCertNo());
			vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(cert.getCertType()));
			vv.setCardType(cd.getCardTypecode());

		}
		String fee="0.00";
		FeeRulesVo f=new FeeRulesVo();
		f.setCardpCode(cd.getCardpCode());
		f.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);
		f.setNow(new Date());
		FeeRules fr=frsm.queryFeeRulesByCardPCodeAndFeeType(f);
		if(fr!=null){
			// 当日交易明细
			TxnDtl td = new TxnDtl();
//			td. setCrdNo("") ;
//			td. setCardSeqNo(""); 
//			td. setCrdUniqueNo("");
			td. setCitizenCardNo(scv.getNewCitizenCardNo());
//			td. setSubaccountNo(String subaccountNo);
			td. setIssCityCd(CardContants.CITY_CODE);		
			td. setTxnCityCd(CardContants.CITY_CODE) ;
//			td. setCrdIndustCd(String crdIndustCd);//卡行业代码
//			td. setAppFlag(bv.getAppFlag());
//			td. setCrdPhysTp(String crdPhysTp) ;//卡物理类型 		  
//			td. setCtSeq(String ctSeq);//中心流水号 			   
//			td. setCtDt(Date ctDt) ;//中心时间
			td. setCashFlag(AccountContants.CASH_FLAG_COLLECT); //现金收付标志 0.无,1.收取 2.支出,3.收支
//			td. setTxnTp(bv.getCrdTxnType());//	卡交易类型
			td. setTxnDt(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));			   
//			td. setTxnBalBef(totalBalance) ;//账户交易前余额		 
//			td. setTxnBalAft(cardWallet.getTotalBalance());			    		
		    try {
		    	td.setTxnAmt(fr.getFeeBln()) ;	//交易金额
			    td.setRealTxnAmt(fr.getFeeBln());//实际交易金额
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(ErrorCode.FEERULES_NOT_EXIST, "收费定义已经过期或未定义");
			}
//			td. setCrdBalBef(bv.getCrdBalBef()) ;//卡交易前 余额
//			td. setCrdBalAft(bv.getCrdBalAft()) ;
//			td. setSetDt(Date setDt);//结算日期			   
			td. setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);//费用类型  0.本金 1:工本费 2.交易手续费 3:租金4:押金			    
//			td. setAcceptTp("06");//受理类型 表示终端的归属，由上传的终端代码决定：01-网点 06-商户
		    td. setAcceptCusNo(activeUser.getBranchNo()) ;//受理商户/网点编号			  
//			td. setTermNo("");//终端代码			    
//			td. setTermSeq(String termSeq) ;//终端流水号			   
//		    td. setSamNo(bv.getSamNo());//			  
//			td. setSamSeq(String samSeq) ;			    
//			td. setTxnFileName("");//交易文件名称
//			td. setPkgRecOrd(Integer pkgRecOrd) ;//所属数据包记录序号 
//		    td. setDivFactor(bv.getDivFactor());
//		    td. setTxnTac(bv.getTxnTac());
//			td. setTxnCharcFld(String txnCharcFld) ;//交易个性域
		    td. setTxnTstFlg(AccountContants.TRANSACTION_TEST_FLAG_COMMON) ;//交易测试标志 "0"-普通; "1"-测试			   
//			td. setErrCode(String errCode);//错误代码 记录级错误			    
//			td. setTxnAdjFlg(String txnAdjFlg);//交易流水标志 "00" 正常 "41" 撤销			   
//			td. setAdjCtSeq(String adjCtSeq) ;//关联中心流水号			    
//			td. setAdjCtDt(Date adjCtDt);//关联中心时间
//			td. setTxnMac1(String txnMac1) ;
//			td. setTxnMac2(String txnMac2);			  
//			td. setAdjSetDt(Date adjSetDt) ;//关联结算日期			   
//			td. setLastTxnCnt(cardWallet.getTotalReloadCnt()) ;//上一次交易卡计数器			   
//			td. setLastTxnDt(Date lastTxnDt) ;//上一次交易时间			 
//			td. setLastTxnAmt(BigDecimal lastTxnAmt) ;//上一次交易金额			   
//			td. setCurrCount(Integer currCount);//当前计数器值 		   
		    td. setWarrantid(cert.getCertNo()) ;//凭证号
//			td. setOutWarrantid(String outWarrantid);//外部凭证号			   
		    td. setOprNo(activeUser.getUserNo().toString());//操作员编号/终端操作员编号 			  
//			td. setLocalTxnSeq(String localTxnSeq);//本地流水号			    
//		    td. setTxnAttr(AccountContants.TXNTP_RECHARGE) ;//交易性质 			   
//			td. setStationId(String stationId) ;//采集点编号
//			td. setPosCarrId(String posCarrId);//POS机载体编号
		    td. setCrdCityCd(CardContants.CITY_CODE);//卡城市代码
		    td. setCardType(cd.getCardTypecode());
		    td. setRsvdFlags(AccountContants.TXNTP_RECHARGE);	//预留标志组		   
//			td. setRsvdFld(String rsvdFld);//保留字段
//			td. setFileGenDate(Date fileGenDate) ;//文件生成日期 	   
//		    td.setTxnType(AccountContants.TRADE_TYPE_BUS) ;//终端交易类型  
		    td.setTxnDate(new SimpleDateFormat("yyyyMMdd").format(new Date())) ;	//交易日期		   
//			td.setOutEntityno(String outEntityno);//外部实体编号
		    td. setBusinessNo(bu.getBusinessNo());//
		    td. setPaymentType(AccountContants.PAYMENT_TYPE_CASH);//支付方式  0 现金 1 兑换券  默认为0
		    td.setPaymentTypeExt(AccountContants.STATUS_INVALID);//支付方式是否扩展 0 否1 是  默认为0
		    tdm.insert(td);
			
			// 交易明细流水表
			TransGlide tg = new TransGlide();
			tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
			//tg.setAccountType(bv.getWalletType());// 账户类型
			//tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
			//tg.setAppFlag(bv.getAppFlag());// 应用标识
			//tg.setAppType(bv.getAppType());// 应用类型
			tg.setBranchNo(activeUser.getBranchNo());
			tg.setBusinessNo(bu.getBusinessNo());//业务流水号
			tg.setCitizenCardNo(scv.getNewCitizenCardNo());// 卡市民卡号
			tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
			try {
				tg.setFeeRuleId(fr.getFeeRuleId());//卡费用规则ID
				tg.setFeeRulesId(fr.getFeeRulesId());//卡费用细则ID
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(ErrorCode.FEERULES_NOT_EXIST, "收费定义已经过期或未定义");
			}
			tg.setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);// 费用类型
			 tg.setIsReturned(AccountContants.STATUS_INVALID);//是否已退费
			tg.setOprNo(activeUser.getUserNo().toString());
			tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金

			tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
			// tg.setRptDate(rptDate);//轧帐日期
			tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
			// tg.setSubaccountNo(subaccountNo);//网点子账号
			// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
			tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
			tg.setTxnAmt(new BigDecimal(scv.getCardCost()));// 交易金额--工本费
			tg.setTxnDt(new Date());// 交易时间
			tg.setTxnTp(AccountContants.TXNTP_COST);// txnTp 交易类型

			tgm.insert(tg);
			
			fee=fr.getFeeBln().toString();
			vv.setTransactionAmount(fr.getFeeBln().toString());
		}
		String str = "\",\"certNo\":\""+cert.getCertNo()+"\",\"busType\":\""+CardContants.getCertTypeNameByCode(cert.getCertType())+"\",\"cardType\":\""
		+cert.getCardTypecode()+"\",\"oldCitizenCardNo\":\""+scv.getOldCitizenCardNo()+"\",\"newCitizenCardNo\":\""+scv.getNewCitizenCardNo()+"\",\"fee\":\""
		+fee+"\",\"net\":\""+activeUser.getBranchName()+"\",\"operator\":\""+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
		String certInfo=null;
		if(scv.getApplyType().equals("1")){
			certInfo="{\"title\":\""+"单笔发卡凭证"+"\",\"type\":\""+"applyRelease"+"\",\"citizenCardNo\":\""+scv.getNewCitizenCardNo()+str;
			cert.setTransCode("单笔发卡");
		}
		else if(scv.getApplyType().equals("4")){
			certInfo="{\"title\":\""+"换卡发卡凭证"+"\",\"type\":\""+"changeAndRelease"+str;
			cert.setTransCode("换卡发卡");
		}else{
			certInfo="{\"title\":\""+"补卡发卡凭证"+"\",\"type\":\""+"supplierAndRelease"+str;
			cert.setTransCode("补卡发卡");	
		}
		cert.setData(certInfo);
		cem.update(cert);
		vv.setNewCitizenCardNo(scv.getNewCitizenCardNo());
		vv.setDate(DateFormatUtils.format(currentTime, "yyyy-MM-dd"));
		vv.setOperator(activeUser.getUserNo().toString());
		vv.setNet(activeUser.getBranchName());
		//vv.setTransactionAmount(new BigDecimal(scv.getCardCost()).toString());
		vv.setTransactionAmount(String.valueOf((new DecimalFormat("0.00")).format(scv.getCardCost())));
		return vv;
	}

	@Override
	public SellCardVo showBaseInfo(SellCardVo scv) {
		// 补卡或者换卡
		if (StringUtils.isNotEmpty(scv.getOldCitizenCardNo())) {
			CardData cd = cdm.queryCardDataByCitizenCardNo(scv.getOldCitizenCardNo());
			CardProdunctDefinition cpd = cpdm.queryCardPCode(cd.getCardpCode());
			CardType ct = ctm.queryCardTypeByCode(cd.getCardTypecode());
			scv.setCardTypeName(ct.getCardTypeName());
			scv.setCardPCodeName(cpd.getCardpName());
			// OnlSubaccountPersonal osp =
			// ospm.querySubAccountByCitizenCardNo(scv.getOldCitizenCardNo());
			// scv.setOldCitizenBalance(osp.getTotalBalance().toString());
			List<AppOpenReg> la = aorm.queryAppOpenRegByRemark2(scv.getOldCitizenCardNo(), AppContants.APP_STATUS_CLOSE_SUPPLEMENTCARD, AppContants.APP_STATUS_CLOSE_CHANGECARD);// 该卡开通的所有应用
			List<String> ls = new ArrayList<>();
			for (AppOpenReg aor : la) {
				AppKind ak = akm.queryAppKindByTypeCode(Integer.valueOf(aor.getAppType()));
				ls.add(ak.getAppFlag());
			}
			scv.setAppCodes(ls);
			BlackListGen bb = blgm.queryBlackListGenBycitizenCardNo(scv.getOldCitizenCardNo());
			scv.setBlackFlagName(BlackListContants.getBlackStatus(bb.getCurStatus()));

			scv.setBlackFlagReason(BlackListContants.getBlackReason(bb.getBlReason()));

		} else {
			// 首次申领
		}
		return scv;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public VoucherVo commitSingleSellCardInfo_Anonymous(SellCardVo scv) throws ApplicationException {
		ActiveUser activeUser = null;
		try {
			activeUser = (ActiveUser) SecurityUtils.getSubject().getSession().getAttribute("activeUser");

		} catch (UnavailableSecurityManagerException e) {
			e.printStackTrace();
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		
		if(activeUser == null){
			activeUser = new ActiveUser();
			activeUser.setUserName("用户");
			activeUser.setLoginName("用户");
			activeUser.setBranchName("互联网端");
			activeUser.setBranchNo("99999999");
			activeUser.setUserNo(99999999);
			activeUser.setUserId(99999999);
		}
		CardData cd = cdm.queryCardDataByCitizenCardNo(scv.getNewCitizenCardNo());
		if(!cd.getCardTypecode().equals(CardContants.CARD_TYPE_ANONYMOUS)){
			throw new ApplicationException(ErrorCode.OTHER_EXCEPTION, "无法出售非不记名卡");
		}
		CardControl cc = ccm.queryCardControlByCitizenCardNo(scv.getNewCitizenCardNo());

		Date currentTime = new Date();

		

		CardManage c1 = new CardManage();
		c1.setProcessId(UUID.randomUUID().toString().replace("-", ""));
		c1.setApplyBranch(activeUser.getBranchName());
		c1.setApplyBranchNo(activeUser.getBranchNo());
		c1.setApplyDate(currentTime);
		c1.setApplyTellerNo(activeUser.getUserNo().toString());
		c1.setApplyWay(CardContants.CLAIM_METHOD_SPORADIC);
		c1.setCardpCode(cd.getCardpCode());
		c1.setCitizenCardNo(scv.getNewCitizenCardNo());
		c1.setProcessCode(CardContants.CARD_PROC_RETRIEVE);
		c1.setProcessName(CardContants.getCardProcNameByCode(CardContants.CARD_PROC_RETRIEVE));
		
		cmm.insert(c1);

		cc.setReleaseDate(currentTime);// 发卡日期
		cc.setCardPosition(CardContants.CARD_POSITION_CITIZEN);
		cc.setCardStatus(CardContants.CARD_STATE_NORMAL);
		cc.setDmgFlag(CardContants.CARD_UNDAMAGED);
		cc.setBlacklistFlag(CardContants.BLACKLIST_FLAG_NORMAL);
		cc.setLastOperator(activeUser.getUserNo().toString());
		cc.setLastDate(currentTime);
		cc.setRemark(" 不记名新卡发放");
		cc.setCurrProcId(c1.getProcessId());
		ccm.updateCardControl(cc);

		// MainAccountPersonal m = new MainAccountPersonal();
		// m.setAccountName("不记名");
		// m.setCustomerNo(cd.getCustomerNo());//不记名
		// m.setAccoBranchNo(activeUser.getBranchNo());
		// m.setAccoTellerNo(activeUser.getUserNo().toString());
		// m.setAccoDate(currentTime);
		// m.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);
		// mapm.insert(m);
		
		

		// 开通应用 默认开通 -公交应用

		AppKind ak = akm.queryAppKindByAppFalg(AppContants.APP_FLAG_TRANSIT);
//		AppOpenReg aor = aorm.queryAppOpenRegByAppType(ak.getAppType().toString());

		AppOpenReg ao = new AppOpenReg();
		ao.setCitizenCardNo(scv.getNewCitizenCardNo());
		ao.setAppType(ak.getAppType().toString());
		ao.setOpenDate(currentTime);

		if (ak.getValidMonthNum() != null) {

			ao.setIsValid(AppContants.APP_ISVALID); // 月份计算
			ao.setValidBegin(currentTime);
			ao.setValidEnd(CommonUtil.willDate(currentTime, ak.getValidMonthNum()));

		} else {
			ao.setIsValid(AppContants.APP_NOVALID); // 月份计算
		}

		// ao.setStopDate(a.getStopDate());//停用日期
		// ao.setRetrieveDate(a.getRetrieveDate());//恢复日期
		ao.setAppStatus(AppContants.APP_STATUS_OPEN);// 应用状态
		ao.setRemark("单笔售卡，默认开通公交3F01应用");
		ao.setCrtOperator(activeUser.getUserNo().toString());
		ao.setCrtDate(currentTime);
		ao.setLastOperator(activeUser.getUserNo().toString());
		ao.setLastDate(currentTime);
		ao.setIsDeposit(AccountContants.IS_DEPOSIT_NO);

		aorm.insert(ao);

		// 钱包1
		SubaccountPersonal cardWallet = new SubaccountPersonal();
		cardWallet.setAccoBranchNo(activeUser.getBranchNo());// 开户网点编号
		cardWallet.setAccoDate(currentTime);// 开户日期
		cardWallet.setAccoTellerNo(activeUser.getUserNo().toString());// 开户柜员号
		//cardWallet.setAccountName("不记名卡");//户名--不记名
		cardWallet.setAccountPw(AccountContants.CARD_WALLET_INT_PASSWORD);// 账户密码
		// cardWallet.setAccountSign(accountSign);//帐户标识
		cardWallet.setAccountStatus(AccountContants.ACCOUNT_STATUS_NORMAL);//帐号状态
		cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 所属钱包类型id 01-电子存折 02-电子钱包
		cardWallet.setAppFlag(akm.queryAppKindByAppFalg("3F01").getAppFlag());// 应用标识
																				// 默认开通公交
		// cardWallet.setCardSeqNo(cappFlagardSeqNo);//卡片序列号
		cardWallet.setCitizenCardNo(cd.getCitizenCardNo());// 市民卡号
		cardWallet.setCityCode(CardContants.CITY_CODE);// 城市代码
		// cardWallet.setClsDate(clsDate);//销户日期
		// cardWallet.setClsTellerNo(clsTellerNo);//销户柜员号
		cardWallet.setCrdBalance(new BigDecimal(0));// 卡面余额
		// cardWallet.setCrdNo(crdNo);//卡内号
		cardWallet.setCurrCount(0);// 当前计数器值
		// cardWallet.setCustomerNo(p.getCustomerNo());//客户编号--不记名
		cardWallet.setErrorDegree((short) 0);// 输错次数
		cardWallet.setFreezeAmount(new BigDecimal(0));// 冻结金额
		// cardWallet.setFreezeDate(freezeDate);//冻结日期
		cardWallet.setFreezeStatus(AccountContants.FREEZE_STATUS_NORMAL);// 冻结标志
		// cardWallet.setInaccEndDate(inaccEndDate);//入账截止日期
		// cardWallet.setInaccEndStatus(inaccEndStatus);// 入账截止状态
		// cardWallet.setLastTransDate(lastTransDate);//最后交易日
		// cardWallet.setLastTransNo(lastTransNo);//最后交易流水号
		// cardWallet.setLossDate(lossDate);//挂失日期
		cardWallet.setLossStatus(CardContants.CARD_STATE_NORMAL);// 挂失状态
		// cardWallet.setMainaccountNo(m.getMainaccountNo());//主帐户号---不记名
		cardWallet.setMaxCount(0);// 最大计数器值
		// cardWallet.setOnlCurrCount(onlCurrCount);//联机交易计数器
		// cardWallet.setOnlTxnDt(onlTxnDt);//最后联机交易时间
		cardWallet.setPasswordStatus(null);// 密码标志
		cardWallet.setProductNumber(0);// 积数
		cardWallet.setRemark("这是备注");
		cardWallet.setSumJe(0);// 消费积分
		cardWallet.setTotalBalance(new BigDecimal(0));// 账面余额
		cardWallet.setTotalConsumeAmt(new BigDecimal(0));// 累计消费金额
		cardWallet.setTotalConsumeCnt(0);// 累计消费笔数
		cardWallet.setTotalExchangeAmt(new BigDecimal(0));// 累计圈存金额
		cardWallet.setTotalExchangeCnt(0);// 累计圈存笔数
		cardWallet.setTotalReloadAmt(new BigDecimal(0));// 累计充值金额
		cardWallet.setTotalReloadCnt(0);// 累计充值笔数
		cardWallet.setValidDate(null);// 有效期
		spm.insert(cardWallet);

		// 钱包2
		cardWallet.setAcType(AccountContants.WALLET_TYPE_ELECTRONIC_WALLET);// 钱包类型
		spm.insert(cardWallet);

		Cert cert = new Cert();
		cert.setCertNo(SequenceNumberUtil.generatorCertNo());
		cert.setCertType(CardContants.SINGLE_CARD);
		cert.setCardpCode(cd.getCardpCode());
		cert.setCardTypecode(cd.getCardTypecode());
		// cert.setName(scv.getCustomerName());
		// cert.setPaperNo(scv.getPaperNo());
		// cert.setPaperType(cf.getCertificateType());
		cert.setBranch(activeUser.getBranchName());
		cert.setBranchNo(activeUser.getBranchNo());
		// cert.setAgentName(scv.getAgentName());
		// cert.setAgentPaperNo(scv.getAgentPaperNo());
		// cert.setAgentPapertype(scv.getAgentPapertype());
		cert.setCardControlId(cc.getCardControlId());
		cert.setCrtDate(new Date());
		cert.setCrtOperator(activeUser.getUserNo().toString());
		cert.setLastOperator(activeUser.getUserNo().toString());
		cert.setLastDate(new Date());
		cem.insert(cert);
		
		Business bu = new Business();
		bu.setBusinessNo(SequenceNumberUtil.generatorBusinessNo());
		// bu.setCustomerNo(cd.getCustomerNo());
		bu.setCardControlId(cc.getCardControlId());
		// bu.setAgentName(scv.getAgentName());
		// bu.setAgentPaperNo(scv.getAgentPaperNo());
		// bu.setAgentPapertype(scv.getAgentPapertype());
		// bu.setAgentPhone(scv.getAgentPhone());
		bu.setBusiNum(1);
		bu.setTellerNo(activeUser.getUserNo().toString());
		// bu.setTransDate(new Date());// 交易日期
		bu.setSeqStatus(CardContants.LSZT_NORMAL);
		bu.setRemark(scv.getRemark());
		bu.setCertNo(cert.getCertNo());
		bm.insert(bu);
		
		FeeRulesVo f=new FeeRulesVo();
		f.setCardpCode(cd.getCardpCode());
		f.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);
		f.setNow(currentTime);
		FeeRules fr=frsm.queryFeeRulesByCardPCodeAndFeeType(f);
		if(fr!=null){
			// 当日交易明细
			TxnDtl td = new TxnDtl();
//			td. setCrdNo("") ;
//			td. setCardSeqNo(""); 
//			td. setCrdUniqueNo("");
//			td. setCitizenCardNo(cd.getCitizenCardNo());
//			td. setSubaccountNo(String subaccountNo);
			td. setIssCityCd(CardContants.CITY_CODE);		
			td. setTxnCityCd(CardContants.CITY_CODE) ;
//			td. setCrdIndustCd(String crdIndustCd);//卡行业代码
//			td. setAppFlag(bv.getAppFlag());
//			td. setCrdPhysTp(String crdPhysTp) ;//卡物理类型 		  
//			td. setCtSeq(String ctSeq);//中心流水号 			   
//			td. setCtDt(Date ctDt) ;//中心时间
			td. setCashFlag(AccountContants.CASH_FLAG_COLLECT); //现金收付标志 0.无,1.收取 2.支出,3.收支
//			td. setTxnTp(bv.getCrdTxnType());//	卡交易类型
			td. setTxnDt(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));			   
//			td. setTxnBalBef(totalBalance) ;//账户交易前余额		 
//			td. setTxnBalAft(cardWallet.getTotalBalance());			    		
		    td.setTxnAmt(fr.getFeeBln()) ;	//交易金额
			td.setRealTxnAmt(fr.getFeeBln());//实际交易金额
			
//			td. setCrdBalBef(bv.getCrdBalBef()) ;//卡交易前 余额
//			td. setCrdBalAft(bv.getCrdBalAft()) ;
//			td. setSetDt(Date setDt);//结算日期			   
			td. setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);//费用类型  0.本金 1:工本费 2.交易手续费 3:租金4:押金			    
			td. setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);//受理类型 表示终端的归属，由上传的终端代码决定：01-网点 06-商户
		    td. setAcceptCusNo(activeUser.getBranchNo()) ;//受理商户/网点编号			  
//			td. setTermNo("");//终端代码			    
//			td. setTermSeq(String termSeq) ;//终端流水号			   
//		    td. setSamNo(bv.getSamNo());//			  
//			td. setSamSeq(String samSeq) ;			    
//			td. setTxnFileName("");//交易文件名称
//			td. setPkgRecOrd(Integer pkgRecOrd) ;//所属数据包记录序号 
//		    td. setDivFactor(bv.getDivFactor());
//		    td. setTxnTac(bv.getTxnTac());
//			td. setTxnCharcFld(String txnCharcFld) ;//交易个性域
		    td. setTxnTstFlg(AccountContants.TRANSACTION_TEST_FLAG_COMMON) ;//交易测试标志 "0"-普通; "1"-测试			   
//			td. setErrCode(String errCode);//错误代码 记录级错误			    
//			td. setTxnAdjFlg(String txnAdjFlg);//交易流水标志 "00" 正常 "41" 撤销			   
//			td. setAdjCtSeq(String adjCtSeq) ;//关联中心流水号			    
//			td. setAdjCtDt(Date adjCtDt);//关联中心时间
//			td. setTxnMac1(String txnMac1) ;
//			td. setTxnMac2(String txnMac2);			  
//			td. setAdjSetDt(Date adjSetDt) ;//关联结算日期			   
//			td. setLastTxnCnt(cardWallet.getTotalReloadCnt()) ;//上一次交易卡计数器			   
//			td. setLastTxnDt(Date lastTxnDt) ;//上一次交易时间			 
//			td. setLastTxnAmt(BigDecimal lastTxnAmt) ;//上一次交易金额			   
//			td. setCurrCount(Integer currCount);//当前计数器值 		   
		    td. setWarrantid(cert.getCertNo()) ;//凭证号
//			td. setOutWarrantid(String outWarrantid);//外部凭证号			   
		    td. setOprNo(activeUser.getUserNo().toString());//操作员编号/终端操作员编号 			  
//			td. setLocalTxnSeq(String localTxnSeq);//本地流水号			    
		    td. setTxnAttr(AccountContants.TXNTP_RECHARGE) ;//交易性质 			   
//			td. setStationId(String stationId) ;//采集点编号
//			td. setPosCarrId(String posCarrId);//POS机载体编号
		    td. setCrdCityCd(CardContants.CITY_CODE);//卡城市代码
		    td. setCardType(cd.getCardTypecode());
		    td. setRsvdFlags(AccountContants.TXNTP_RECHARGE);	//预留标志组		   
//			td. setRsvdFld(String rsvdFld);//保留字段
//			td. setFileGenDate(Date fileGenDate) ;//文件生成日期 	   
//		    td.setTxnType(AccountContants.TRADE_TYPE_BUS) ;//终端交易类型  
		    td.setTxnDate(new SimpleDateFormat("yyyyMMdd").format(new Date())) ;	//交易日期		   
//			td.setOutEntityno(String outEntityno);//外部实体编号
		    td. setBusinessNo(bu.getBusinessNo());//
		    td. setPaymentType(AccountContants.PAYMENT_TYPE_CASH);//支付方式  0 现金 1 兑换券  默认为0
		    td.setPaymentTypeExt(AccountContants.STATUS_INVALID);//支付方式是否扩展 0 否1 是  默认为0
		    tdm.insert(td);
			// 交易明细流水表
			TransGlide tg = new TransGlide();
			tg.setAcceptTp(AccountContants.ACCEPTANCE_TYPE_NET);// 受理类型
			//tg.setAccountType(bv.getWalletType());// 账户类型
			//tg.setAllowReturn(AccountContants.STATUS_INVALID);//不可退费
			//tg.setAppFlag(bv.getAppFlag());// 应用标识
			//tg.setAppType(bv.getAppType());// 应用类型
			tg.setBranchNo(activeUser.getBranchNo());
			tg.setBusinessNo(bu.getBusinessNo());//业务流水号
			tg.setCitizenCardNo(cd.getCitizenCardNo());// 旧卡市民卡号
			tg.setCashFlag(AccountContants.CASH_FLAG_COLLECT);// 现金收付标志
			tg.setFeeRuleId(fr.getFeeRuleId());//卡费用规则ID
			tg.setFeeRulesId(fr.getFeeRulesId());//卡费用细则ID
			tg.setFeeTp(AccountContants.FEE_TYPE_NOMINAL_FEE);// 费用类型
			 tg.setIsReturned(AccountContants.STATUS_INVALID);//是否已退费
			tg.setOprNo(activeUser.getUserNo().toString());
			tg.setPaymentType(AccountContants.PAYMENT_TYPE_CASH);// 现金

			tg.setPaymentTypeExt(AccountContants.STATUS_INVALID);
			// tg.setRptDate(rptDate);//轧帐日期
			tg.setRptFlag(AccountContants.RPT_FLAG_NO);// 轧帐标识 0未过账
			// tg.setSubaccountNo(subaccountNo);//网点子账号
			// tg.setReturnTransGlideId(returnTransGlideId);//退费交易明细流水ID
			tg.setTxnAdjFlg(AccountContants.TRANSACTION_FLOW_FLAG_NORMAL);// 交易流水标识
			tg.setTxnAmt(new BigDecimal(scv.getCardCost()));// 交易金额
			tg.setTxnDt(currentTime);// 交易时间
			tg.setTxnTp(AccountContants.TXNTP_COST);// txnTp 交易类型

			tgm.insert(tg);
		}
		c1.setCertNo(cert.getCertNo());
		c1.setBusinessNo(bu.getBusinessNo());
		cmm.update(c1);
		
		String str = "{\"title\":\""+"不记名售卡凭证"+"\",\"type\":\""+"sellCard"+"\",\"certNo\":\""+cert.getCertNo()+"\",\"busType\":\""
		+CardContants.getCertTypeNameByCode(cert.getCertType())+"\",\"cardType\":\""+cert.getCardTypecode()+"\",\"citizenCardNo\":\""
		+scv.getNewCitizenCardNo()+"\",\"fee\":\""+(new DecimalFormat("0.00")).format(scv.getCardCost())+"\",\"net\":\""
		+activeUser.getBranchName()+"\",\"operator\":\""+activeUser.getUserNo().toString()+"\",\"date\":\""+DateFormatUtils.format(new Date(), "yyyy-MM-dd")+"\"}";
		cert.setData(str);
		cert.setTransCode("不记名售卡");
		cert.setBusinessNo(bu.getBusinessNo());
		cem.update(cert);

		VoucherVo vv = new VoucherVo();
		vv.setCertNo(cert.getCertNo());
		vv.setBusinessTypeName(CardContants.getCertTypeNameByCode(cert.getCertType()));
		vv.setCardType(cd.getCardTypecode());
		 vv.setNewCitizenCardNo(scv.getNewCitizenCardNo());
		// vv.setExpectCardDate(ccc.getTime());
		vv.setDate(DateFormatUtils.format(currentTime, "yyyy-MM-dd"));
		vv.setOperator(activeUser.getUserNo().toString());
		vv.setNet(activeUser.getBranchName());
		//vv.setTransactionAmount(new BigDecimal(scv.getCardCost()).toString());
		vv.setTransactionAmount(String.valueOf((new DecimalFormat("0.00")).format(scv.getCardCost())));
		return vv;
	}

	@Override
	public ReadCardVo queryCardDataByCitizenCardNo(String citizenCardNo) throws ApplicationException {
		ReadCardVo readCardVo=qcm.queryCardDataByCitizenCardNo(citizenCardNo);
		if(readCardVo==null){
			throw new ApplicationException(ErrorCode.CARDDATA_NO_EXTIST, "此卡数据不存在");
		}
		if(!readCardVo.getCardStatus().equals(CardContants.CARD_STATE_DISABLED)){
			throw new ApplicationException(ErrorCode.CARD_USEING,"此卡已启用");
		}
		if(readCardVo.getCardStatus().equals(CardContants.CARD_STATE_DISABLED)){
			if(!readCardVo.getClaimStatus().equals(CardContants.CLAIM_STATUS_TOGIVE)){
				throw new ApplicationException(ErrorCode.OTHER_EXCEPTION,"此卡未待发放状态");
			}
		}
		FeeRulesVo vo=new FeeRulesVo();
		vo.setCardpCode(readCardVo.getCardPCode());
		vo.setFeeType(AccountContants.FEE_TYPE_NOMINAL_FEE);//工本费
		vo.setNow(new Date());
		FeeRules rules=frsm.queryFeeRulesByCardPCodeAndFeeType(vo);
		if(rules!=null){
			readCardVo.setCardCost(rules.getFeeBln());
		}else{
			readCardVo.setCardCost(new BigDecimal(0));
		}
		
		return readCardVo;
	}

	
	@Override
	public File downloadSellCard(String root,String applyBatchNo,String fileName) {
		
		List<Personal> list_personal = pm.getPersonalByApplyBatchNo(applyBatchNo);
		List<Certificate> list_Certificate = cfm.queryAllCertificates();
		List<CardData> list_CardData = cdm.queryCardDataByApplyBatchNo_list(applyBatchNo);
		List<DownloadBatchSellCardVo> list_view = new ArrayList<>();
		for(Personal p:list_personal){
			
			DownloadBatchSellCardVo v = new DownloadBatchSellCardVo(p.getCustomerName(),p.getPaperNo(),p.getMobile());
			v.setGender(p.getGender() == CardContants.GENDER_MALE ? "男" : "女");
			a:for(CardData cd :list_CardData){
				if(p.getCustomerNo().equals(cd.getCustomerNo())){
					v.setCitizenCardNo(cd.getCitizenCardNo());
					break a;
				}
			}
			
			b:for(Certificate cf :list_Certificate){
				if(p.getPaperType().equals(cf.getCertificateType())){
					v.setPaperType(cf.getCertificatesName());
					break b;
				}
			}
			
			list_view.add(v);
		}
		
		
		return ExportExcel.batchSellCardTemplate(list_view, fileName,root);
	}

}
